﻿import d3 from '@/components/d3-util'
import '@/components/radialIndicator'

const chart = function (dom_container, options) {
  var opt = {
    tipFormat: null,
    MeasureMap: null
  };
  _.extend(opt, options);
  if (opt.config.ThemeType === 999)
    opt.config.ThemeType = "circle";

  if (!opt.size) {
    opt.size = d3.util.getInnerBoxDim(dom_container);
  }

  var rowData = opt.data.sourceData[0];
  var mainValue = rowData[opt.rowMeasure.name];
  var mainTitle = opt.rowMeasure.name;

  var chart_opt = {};
  var myChart = $(dom_container);
  var setOption = function (opt) {
    chart_opt = $.extend(chart_opt, opt);

    if (opt.config.ThemeType === "circle") {
      //http://ignitersworld.com/lab/radialIndicator.html
      //http://www.jq22.com/jquery-info4495
      var minValue = 0;
      var maxValue = 100;
      var percentage = true;
      if (opt.config && opt.config.ShowConfig
        && opt.config.ShowConfig.StatisticType && opt.config.ShowConfig.StatisticType === "0") {
        //统计值
        maxValue = opt.config.ShowConfig.StatisticMaxValue;
        percentage = false;
      }
      var radialObj = radialIndicator(myChart, {
        //radius: opt.size.height * 0.4, //圆半径
        radius: opt.size.height * 0.25, //圆半径
        barColor: opt.config.GlobalColor,    //进度（数据主色）颜色
        barBgColor: opt.config.axisStyle.tickColor,    //进度背景颜色
        barWidth: 10,   //进度宽度
        initValue: 0,   //初始值
        minValue: minValue,
        maxValue: maxValue,
        roundCorner: true,  //显示圆角
        percentage: percentage,    //显示百分比
        //displayNumber:true,  //显示文本
        format: function (value) {
          var valueText = Number(mainValue).toMeasureFormart(opt.MeasureMap[mainTitle].numberFormat);
          //标题
          if (opt.config && opt.config.ShowConfig
            && opt.config.ShowConfig.ShowTitle && opt.config.ShowConfig.ShowTitle !== "") {
            valueText = opt.config.ShowConfig.ShowTitle + '\r' + valueText;
          }
          return valueText;
        },
        //format: "销售额\r ###%",
        fontSize: opt.config.axisStyle.fontSize,
        fontColor: opt.config.axisStyle.fontColor,
        otherConfig: opt.config
      });


      radialObj.animate(mainValue);
      //垂直居中
      radialObj.canElm.style = "left: 0; right: 0; top: 0; bottom: 0; margin: auto; position: absolute;";
    } else {
      //https://github.com/glarios/jQMeter
      //https://blog.csdn.net/cddcj/article/details/52795379
      var barWidth = opt.config.axisStyle.fontSize * 2;
      var $process = $("<div></div>");
      myChart.append($process);
      var goalNum = '100';
      if (opt.config && opt.config.ShowConfig
        && opt.config.ShowConfig.StatisticMaxValue
        && opt.config.ShowConfig.StatisticMaxValue !== ""
        && opt.config.ShowConfig.StatisticType === "0") {
        goalNum = opt.config.ShowConfig.StatisticMaxValue;
      }

      $process.jQMeter({
        goal: goalNum,    //最大值
        raised: parseInt(mainValue) + '',   //最小值
        orientation: opt.config.ThemeType,    //horizontal==水平，vertical==垂直，circle==圆
        meterOrientation: opt.config.ThemeType,    //horizontal==水平，vertical==垂直，circle==圆
        bgColor: opt.config.axisStyle.tickColor,    //进度背景颜色
        barColor: opt.config.GlobalColor,   //进度（数据主色）颜色
        displayTotal: false,    //进取条，百分比文字
        width: opt.config.ThemeType === "horizontal" ? "100%" : barWidth + "px",
        height: opt.config.ThemeType === "horizontal" ? barWidth + "px" : "100%"
      });

      myChart.find('.outer-therm').css("margin", "auto");
      myChart.find('span').css({
        "color": opt.config.axisStyle.fontColor,
        "font-size": opt.config.axisStyle.fontSize * 1.4 + 'px'
      });

      //当前数值
      if (opt.config && opt.config.ShowConfig
        && opt.config.ShowConfig.StatisticType && opt.config.ShowConfig.StatisticType === "0") {
        $process.prepend($("<div class='processNum' style='padding: 6px 0px;color:" + opt.config.GlobalColor + ";font-size: " + opt.config.axisStyle.fontSize + "px;'>" + Number(mainValue).toMeasureFormart(opt.MeasureMap[mainTitle].numberFormat) + "</div>"));
      }
      //标题
      if (opt.config && opt.config.ShowConfig
        && opt.config.ShowConfig.ShowTitle && opt.config.ShowConfig.ShowTitle !== "") {
        $process.prepend($("<div class='processTitle' style='font-size: " + opt.config.axisStyle.fontSize * 1.6 + "px;'>" + opt.config.ShowConfig.ShowTitle + "</div>"));
      }
      if (opt.config.ThemeType === "vertical") {
        var processLeft = $process.find('.outer-therm').offset().left / 2;
        $process.css({"height": "calc(100% - 0px)"});
        $process.find('.processNum').css({
          "left": (processLeft - barWidth) + "px",
          "writing-mode": "vertical-lr",
          "position": "absolute",
          "padding": "0px"
        });
        $process.find('.processTitle').css({
          "left": (processLeft - barWidth * 2) + "px",
          "writing-mode": "vertical-lr",
          "position": "absolute"
        });
      }
    }
  }

  if (opt) {
    setOption(opt);
  }

  myChart.on('click', function () {
    console.log(arguments);
    if (myChart.onselected) {
      //当前维度
      myChart.onselected([{
        field: opt.rowMeasure,
        value: [mainValue]
      }]);
    }

    console.log(opt.rowMeasure);
    console.log([mainValue]);
  });

  this.setOption = setOption;
  this.removeChart = function () {
  }

};
/**
 * 进度图
 */

const buildChart = function (svgSelector, data, columnFields, rowFields, options) {
  var cOpt = {};

  var config = options.chartConfig;
  if (!config || !config.GlobalColor) {
    config = {
      GlobalColor: "#4E79A7",
      MultiColors: ["#4E79A7", "#A0CBE8", "#F28E2B", "#FFBE7D", "#59A14F", "#8CD17D", "#B6992D", "#F1CE63", "#499894", "#86BCB6", "#E15759", "#FF9D9A", "#79706E", "#BAB0AC", "#D37295", "#FABFD2", "#B07AA1", "#D4A6C8", "#9D7660", "#D7B5A6"],
      scale: 0.8,
      axisStyle: {
        tickColor: "#000",
        fontColor: "#000",
        fontFamily: "Arial",
        fontSize: 12
      },
      textStyle: {
        "display": "none",
        "font-family": "Arial",
        "font-size": 12,
        "font-style": "normal",
        "font-weight": "normal",
        "fill": "#333",
        "position": "top"
      },
      ThemeType: 999
    }
  }
  cOpt.config = config;

  var dimension = (columnFields.length > 0 && columnFields[0].slaveType === 0) ? columnFields[0] : rowFields[0];
  var measure = (rowFields.length > 0 && rowFields[0].slaveType === 1) ? rowFields[0] : columnFields[0];
  cOpt.colDimension = dimension;
  cOpt.rowMeasure = measure;

  //获取所有度量字段
  var measureFields_c = Enumerable.from(columnFields).where(
    function (d) {
      if (d.slaveType === 1) {
        return d;
      }
    }
  ).toArray();
  var measureFields_r = Enumerable.from(rowFields).where(
    function (d) {
      if (d.slaveType === 1) {
        return d;
      }
    }
  ).toArray();
  var measureFields = measureFields_c.concat(measureFields_r);
  var measureMap = {};
  measureFields.forEach(function (f) {
    measureMap[f.name] = f;
  });
  cOpt.MeasureMap = measureMap;

  const sourceData = data.concat();//原始数据
  cOpt.data = {sourceData: sourceData};

  const dom_container = $(svgSelector).children('#chart')[0];
  const chartInstance = new chart(dom_container, cOpt);
  return chartInstance;
}

export const ProcessChart = {
  build: buildChart
}

